package smsBean;


import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.Hashtable;
import java.util.Vector;

import control.Command;
import dbmanager.ChekInMaster;
import dbmanager.DBManager;

import utility.ConvertToLower;
import utility.Index;
import utility.MessageGenerator;



public class SmsTrans_property_details extends SubSmsBean
{

	private String tid = "no$";
	private String PropertySPchar="";
	private String masterTable = "transaction";
	private String tpl_tableName = "trans_property_details";
	
	private Hashtable<Object,Object> PropertyMap ;
	
	private Vector<Object> TransPropertyVector = new Vector<Object>();
	
	private Vector<Object> OldTransPropertyVector = new Vector<Object>();
	private Vector<Object> NewTransPropertyVector = new Vector<Object>();
	
	private Hashtable<Object,Object> ViewHashtable = new Hashtable<Object, Object>();
	 
	//Trans_property_details_Bean tplBean;
	
	public SmsTrans_property_details()
	{}
	
	public SmsTrans_property_details(DBManager sqldb)
	{
		this.sqlDB = sqldb;		
	}
	
	public SmsTrans_property_details(DBManager sqldb,String msg,String process,String Request)
	{	
		this.request = Request;
		this.process = process;
		this.sqlDB = sqldb;
		message = msg;
		
	}
	
	
	
	/**
	  * 
	  * In initializeToAdd method of Trans_property_details put the hashMap in 
	  * PropertyMap hashtable.
	  * @return PropertyMap is a Hashtable which stores object of Trans_property_details
	  * class.
	  * hashtable contains the all the fields of Trans_property_details which presents in
	  * given message e.g. Tid,pid,pv,vt,ref. 
	  * 
	 */
	public Hashtable<Object, Object> initializeToAdd()
	{
	
		PropertyMap = new Hashtable<Object, Object>();
		Hashtable<Object,Object> TempMap = new Hashtable<Object, Object>();
		TempMap = initTransactionProperty();
		if(TempMap.containsKey("ErrorInput"))
		{
			return TempMap;
		}		
		
		Command cp = new Command(masterTable,sqlDB);
		String tidmsg=message.substring(0,Index.indexOf(message, PropertySPchar));
		PropertyMap = cp.getHashCommand(request,tidmsg,process); 
		if(PropertyMap.containsKey("ErrorInput"))
		{
			return PropertyMap;
		}
		PropertyMap = ConvertToLower.convertHashKey(PropertyMap);
		ChekInMaster check = new ChekInMaster(sqlDB);
		tid = PropertyMap.get("tid").toString();	
		
		TempMap.put("id", tid);
		
		if(!check.isInProperty_details(TempMap, "transaction"))
		{
			TempMap.put("ErrorInput", "Transaction ID not Present");
			return TempMap;
		}
		
		insertTid(tid);
		
	
		return PropertyMap;
	}
	
	
	/**
	 * this function inserts tid in each hashtable given in PropertyVector
	 *  @param tid - stores tid as a string value
	 */
	@SuppressWarnings("unchecked")
	private void insertTid(String tid)
	{
		for(Object object : TransPropertyVector)
		{
			Hashtable<Object,Object> tempHash = (Hashtable<Object, Object>)object;
			tempHash.put("tid",tid);			
		}
		
	}
	
	
	/**
	 * In this method it splits all properties and creates an object of each property
	 * which stores in  hashmap.Then add these hashmap in TPropertyList vector. 
	 * PropertyMap s a Hashtable which stores objects of Trans_property_details class.
	 * Then, this PropertyMap object is stored in Vector TPropertyList.
	 * @return PropertyMap 
	 */
	
	public Hashtable<Object, Object> initTransactionProperty()
	{
		
		PropertyMap = new Hashtable<Object, Object>();
		int index=0;
		int count;
		
		Command cp = new Command(masterTable,sqlDB);
		count = cp.getCountof(message, tpl_tableName, process);//	getCount();
		if(count!=0)
		{
			PropertySPchar=cp.getSPchar();
			index = Index.indexOf(message,PropertySPchar,index+1);
		}
		
		String msg="";
		while(count!=0)
		{
			if(index==-1)
			{
				break;
			}
			count--;
			try
			{
				int start=0;
				int end=0;
				start = index;
				msg = message.substring(start+1);
				if(msg.contains(PropertySPchar))
				{
					end = Index.indexOf(msg,PropertySPchar)+start;
					msg = message.substring(start,end+1);
				}
				else
				{
					msg= message.substring(start);			
				}
				index= end+1;
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
			Hashtable<Object,Object> PropertyMap1 = new Hashtable<Object, Object>();
			  
			PropertyMap1.putAll(cp.getHashCommand(tpl_tableName,msg,process));
			if(PropertyMap1.containsKey("ErrorInput"))
			{
				PropertyMap.put("ErrorInput", PropertyMap1.get("ErrorInput"));
				return PropertyMap;
			}
			
			Hashtable<Object, Object> tempProperty1 = new Hashtable<Object, Object>();
			tempProperty1 = cp.checkError(PropertyMap1, tpl_tableName);
			if (tempProperty1.containsKey("ErrorInput")) 
			{
				return tempProperty1;
			}
			
				TransPropertyVector.add(PropertyMap1);
			
		}
		return PropertyMap;
	}	
	
	
	/**
	 * initializeToUpdate() creates two vectors(old & new) of hashtables of different properties to be updated
	 */
	public StringBuffer initializeToUpdate()
	{
		
		int count;
		ResultSet rs = null;
		String pipeChar = null;
		Command cp = new Command(request,sqlDB);
		String msg=" ";
		Hashtable<Object,Object> TempHash = new Hashtable<Object,Object>();
		
		try
		{	
			rs = sqlDB.getSelect("select fieldname,spchar,order1 from command where msgtype='" + tpl_tableName + "' and from_master='yes' and process='add' order by order1");					
			rs.next();
			pipeChar = rs.getString("spchar");
			rs.close();
		}
		catch(Exception e)
		{
			System.out.println("Pipe Char is not Found in Database");
		}		
	
		int index=0;
		count = cp.getCountof(message, tpl_tableName, process);//	getCount();
		if(count!=0)
		{
			try 
			{
				rs = sqlDB.getSelect("select fieldname,spchar,order1 from command where msgtype='"+ tpl_tableName+ "' and from_master='yes' and process='mod' and order1>0 order by order1");
				rs.next();
				PropertySPchar = rs.getString("spchar");
				rs.close();
			} 
			catch (SQLException e) {
			}
			index = Index.indexOf(message,PropertySPchar,index+1);
		}
		
		try 
		{
			tid=message.substring(0,index);
	
			TempHash = cp.getHashCommand(tpl_tableName,tid, "add");
			
			if(TempHash.containsKey("ErrorInput"))
		 	{
				return new StringBuffer(TempHash.toString());
			}
			tid = TempHash.get("tid").toString();
		} 
		catch (Exception e1) 
		{
			return new StringBuffer("Please Check the Transaction ID ");
		}
		while(count!=0)
		{
			Hashtable<Object,Object> newTransactionMap = new Hashtable<Object,Object>(); /** It will get stores new mesage for Update.*/
			Hashtable<Object,Object> oldTransactionMap = new Hashtable<Object, Object>(); /** It will get stores old mesage for Update.*/
		
			newTransactionMap.put("tid", tid);
			
			if(index==-1)
			{
				break;
			}
			count--;
			try
			{
				int start=0;
				int end=0;
				start = index;
				msg = message.substring(start+1);
				if(msg.contains(PropertySPchar))
				{
					end = Index.indexOf(msg,PropertySPchar)+start;
					msg = message.substring(start,end+1);
				}
				else
				{
					msg= message.substring(start);				
				}
				index= end+1;
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			String msg1="";
			String msg2="";
			int start=0;
			boolean TYPEFLAG = false;
		
			if(msg.contains(pipeChar))
			{
				int end1=0;
				end1 = Index.indexOf(msg,pipeChar,end1+1);
				if(end1==-1)
				{
					newTransactionMap.put("ErrorInput","Item should insert");
				}
				msg1 = msg.substring(start, end1);
				
				TYPEFLAG = true;
			}
			else
			{
				msg1=msg;
			}
		
	        newTransactionMap.putAll(cp.getHashCommand(tpl_tableName, msg1, process));
	    	if(newTransactionMap.containsKey("ErrorInput"))
		 	{
				return new StringBuffer(newTransactionMap.toString());
			}
	        newTransactionMap = ConvertToLower.convertHashKey(newTransactionMap);
	        PropertyMap = new Hashtable<Object, Object>();
            PropertyMap = cp.checkError(newTransactionMap, tpl_tableName); 
			if (PropertyMap.containsKey("ErrorInput")) 
			{
				return new StringBuffer(PropertyMap.toString());
			}
			if(TYPEFLAG)
			{
				start = Index.indexOf(msg, pipeChar, start + 1);
		        msg2 = msg.substring(start, msg.length());
		        oldTransactionMap.putAll(cp.getHashCommand(tpl_tableName, msg2, "add"));
		    	if(oldTransactionMap.containsKey("ErrorInput"))
			 	{
					return new StringBuffer(oldTransactionMap.toString());
				}
		        oldTransactionMap = ConvertToLower.convertHashKey(oldTransactionMap);
		      
		         PropertyMap.putAll(cp.checkError(oldTransactionMap , tpl_tableName));
		        if(PropertyMap.containsKey("ErrorInput"))
				{
					return new StringBuffer(PropertyMap.toString());
				}
		        oldTransactionMap.put("tid", tid);
		        
		        Hashtable<Object, Object> temp = new Hashtable<Object, Object>();
		        temp.putAll(oldTransactionMap);
		        
		        OldTransPropertyVector.add(oldTransactionMap);
			}   
						
		  	Hashtable<Object, Object> temp1 = new Hashtable<Object, Object>();    			
			temp1.putAll(newTransactionMap);			
			
			NewTransPropertyVector.add(newTransactionMap);			
		}
		return sbrDTB;
	}
	
	
	/**
	 * initializeToView() creates hashtables of transaction properties object to be viewed 
	 * @return stringbuffer containing details of transaction properties to be viewed  
	 */
	public StringBuffer initializeToView() 
	{

		StringBuffer sbrProperty=new StringBuffer();		
		
		Command cp=new Command(message,sqlDB);
		Hashtable<Object, Object> PropertyMap = new Hashtable<Object, Object>();
		PropertyMap.putAll(cp.getHashCommand(tpl_tableName, message, process));
		if(PropertyMap.containsKey("ErrorInput"))
		{
			sbrProperty.append(PropertyMap.get("ErrorInput"));
			return sbrProperty;
		}
		
		if(PropertyMap.containsKey("ErrorInput"))
		{			
			sbrProperty.append("Error in input str");
			return sbrProperty;
		}
		ViewHashtable.putAll(PropertyMap);		
		return sbrProperty;
	}
	
	
	public String getId() {
		return tid;
	}
	
	public Vector<Object> getPropertyVector()
	{	
		return TransPropertyVector;
	}
	
	public Vector<Object> getOldPropertyVector() {
		
		return OldTransPropertyVector;
	}
	
	public Vector<Object> getNewPropertyVector() {
		
		return NewTransPropertyVector;
	}
	
	public Hashtable<Object,Object> getViewHashtable() {
		return ViewHashtable;		
	}

	
	public Hashtable<Object, Object> initializeToDelete() {
		// TODO Auto-generated method stub
		return null;
	}
	

	/**
	 * is called when process is to insert in database
	 */
	//@SuppressWarnings("unchecked")
	/*public void setProcessToAdd()
	{	
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		
		//add	
		PropertyMap = new Hashtable<Object, Object>();
		PropertyMap.putAll(initializeToAdd());
		
		System.out.println();
		System.out.println(TransPropertyVector);
		System.out.println();		

		if(!PropertyMap.containsKey("ErrorInput"))
		{
			tplBean = new Trans_property_details_Bean();
			
			for(Object object : TransPropertyVector)
			{
				Hashtable<Object ,Object> temp = (Hashtable<Object, Object>)object;
				tplBean.setPropertyVector(temp);	
			}
			tplBean.setDBManager(sqlDB);
			tplBean.setReqParam(reqParam);
			tplBean.setProcess(process);
			
			tplBean.insert();
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMs.tablename","Trans_property_details","processAdd",t.duration());
		
	}*/
	
	/**
	 * is called when process is to update in database
	 */
	/*public void setProcessToUpdate()
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		
		//mod			
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToUpdate());
		
		System.out.println("old "+OldTransPropertyVector);
		System.out.println("new "+NewTransPropertyVector);		
			
		tplBean = new Trans_property_details_Bean();
		
		tplBean.setDBManager(sqlDB);
		tplBean.setReqParam(reqParam);
		tplBean.setProcess(process);
		
		if(!OldTransPropertyVector.isEmpty())
			tplBean.setOldPropertyVector(OldTransPropertyVector);	
		
		if(!NewTransPropertyVector.isEmpty())
			tplBean.setNewPropertyVector(NewTransPropertyVector);	
		
		tplBean.update();
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMs.tablename","Trans_property_details","processMod",t.duration());
		
	}*/
	
	
	/*@SuppressWarnings("unchecked")
	public void processSms()
	{		
		//add	
		if(process.equalsIgnoreCase("add"))
			processAdd();
		else
			processMod();//mod		
	}
	
	public void setProcessToView()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
				
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToView());
		
		System.out.println(ViewHashtable);		
		
		tplBean = new Trans_property_details_Bean();
		
		tplBean.setDBManager(sqlDB);
		tplBean.setReqParam(reqParam);
		tplBean.setProcess(process);
		
		
		sbrDTB.append(tplBean.view());
		System.out.println(sbrDTB);
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Transaction_details","getView",t.duration());
		
	}
	*/
	public StringBuffer generatesms(StringBuffer strbuffer)
	{
		StringBuffer stringbuffer= new StringBuffer();
		String splitbuffer[] = strbuffer.toString().split("\n");
		if(splitbuffer.length>0)
		{
			try 
			{
				String splitheading[] = splitbuffer[0].split("\t");
				
				StringBuffer heading = new StringBuffer();
				StringBuffer Field = new StringBuffer();
				
				
				MessageGenerator msg=new MessageGenerator(sqlDB);
				for(int i=1;i<splitbuffer.length;i++)
				{
					Hashtable<Object , Object> table =new Hashtable<Object, Object>();
				  	String splitfield[] =splitbuffer[i].split("\t");
				  	for(int j=0;j<splitfield.length;j++)
				  	{	
				  		table.put("pid",splitheading[j]);
				  		table.put("pv",splitfield[j]);
				  	}	
				  	stringbuffer.append(msg.convertToMessage(tpl_tableName,"view",table));
				}	
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
		}
		return stringbuffer;
		
	}
	
}
